//
//  ViewController.m
//  XueyingDemo
//
//  Created by wuxueying on 9/14/15.
//  Copyright (c) 2015 xueying wu. All rights reserved.
//

#import "ViewController.h"
#import "HomeTableViewCell.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "LDCalendarView.h"
#import "NSDate+extend.h"
#import "CCEaseRefresh.h"
#import "RxWebViewController.h"
#import "LxDBAnything.h"
#import "BannerViewController.h"
#import "JHCustomMenu.h"
#import "ColumnViewController.h"
#import "Header.h"
#import "LCNavigationController.h"
#import "PellTableViewSelect.h"
#import "BHBPopView.h"
#import "DisperseBtn.h"
#import "YyxHeaderRefresh.h"
#import "GuideView.h"
#import "AYSlidingPickerView.h"
#import "AS_Sheet.h"

@interface ViewController () <ABPeoplePickerNavigationControllerDelegate, JHCustomMenuDelegate> {
    NSArray *_demoTitleArray;
    GuideView *markView;
}
@property (nonatomic) AYSlidingPickerView *pickerView;
@property (strong, nonatomic) YyxHeaderRefresh *refresh;
@property (weak, nonatomic) DisperseBtn *disView;
@property (nonatomic, strong) JHCustomMenu *menu;
@property (nonatomic, strong)LDCalendarView    *calendarView;//日历控件
@property (strong, nonatomic) CCEaseRefresh *refreshView;
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpPickerView];
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"001.png"] style:UIBarButtonItemStylePlain target:self action:@selector(showSchoolList:)];
//    
//    self.navigationItem.leftBarButtonItem = leftItem;
    
    DisperseBtn *disView = [[DisperseBtn alloc]init];
    disView.frame = CGRectMake(100, 100, 50, 50);
    disView.borderRect = self.view.frame;
    disView.closeImage = [UIImage imageNamed:@"icon2"];
    disView.openImage = [UIImage imageNamed:@"icon3"];
    
    [self.view addSubview:disView];
    _disView = disView;
    [self setDisViewButtonsNum:3];
    
    self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(64, 0, 0, 0);
    
    // 网易刷新
//    self.refreshView = [[CCEaseRefresh alloc] initInScrollView:self.tableView];
//    [self.refreshView addTarget:self action:@selector(dropViewDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
//    [self.refreshView beginRefreshing];
    
    // 猫眼刷新
    self.refresh = [YyxHeaderRefresh header];
    self.refresh.tableView = self.tableView;
    CATWEAKSELF
    self.refresh.beginRefreshingBlock = ^(YyxHeaderRefresh *refreshView){
        [weakSelf dd];
    };
    
    [self addGuideView];
    
    _demoTitleArray = @[@[@"1.BannerViewController--无限循环图片浏览",@"BannerViewController"],
                        @[@"2.获取联系人信息"],
                        @[@"3.VisualEffectViewController--毛玻璃效果",@"VisualEffectViewController"],
                        @[@"4.SpinnerViewController--加载loading动画",@"SpinnerViewController"],
                        @[@"5.CalenderViewController--日历选择",@"CalenderViewController"],
                        @[@"6.ICarouselViewController--图片滚动选择",@"ICarouselViewController"],
                        @[@"7.PageTableViewController--下拉显示全图tableView",@"PageTableViewController"],
                        @[@"8.日历选择样式"],
                        @[@"9.ScrollLabelViewController--滚动label",@"ScrollLabelViewController"],
                        @[@"10.InputDodgerViewController--移动TextField",@"InputDodgerViewController"],
                        @[@"11.RapidSelectViewController--长按删除cell",@"RapidSelectViewController"],
                        @[@"12.LoadingHubViewController---加载的动画",@"LoadingHubViewController"],
                        @[@"13.VideoBackgroundViewController---背景视频",@"VideoBackgroundViewController"],
                        @[@"14.RevelImageViewController---动画显示头像",@"RevelImageViewController"],
                        @[@"15.PieChartViewController---PieChart",@"PieChartViewController"],
                        @[@"16.ImagePickerViewController---图片选择",@"ImagePickerViewController"],
                        @[@"17.SLButtonViewController---loadingButton",@"SLButtonViewController"],
                        @[@"18.KnockDetectorViewController---摇一摇检测",@"KnockDetectorViewController"],
                        @[@"19.RxWebView",@""],
                        @[@"20.LxDBAnything",@""],
                        @[@"21.BEMMainViewController---checkbox",@"BEMMainViewController"],
                        @[@"22.CircleTimerViewController",@"CircleTimerViewController"],
                        @[@"23.FlatSlideViewController--滑动条",@"FlatSlideViewController"],
                        @[@"24.ChinaCityViewController--选择城市",@"ChinaCityViewController"],
                        @[@"25.HZQDatePickerViewController--日历选择",@"HZQDatePickerViewController"],
                        @[@"26.StitchingImageViewController--合并头像",@"StitchingImageViewController"],
                        @[@"28.MinToMaxSliderViewController--滑动的slider",@"MinToMaxSliderViewController"],
                        @[@"29.ColumnView--网易选择tab",@""],
                        @[@"30.LoadingAnimationStepViewController--动画",@"LoadingAnimationStepViewController"],
                        @[@"31.CustomKeyboardViewController--自定义数字键盘",@"CustomKeyboardViewController"],
                        @[@"32.MergeVideoAndMusicViewController--合成视频语音",@"MergeVideoAndMusicViewController"],
                        @[@"33.PluseViewController---扩张动画",@"PluseViewController"],
                        @[@"34.CustomPopView---QQ"],
                        @[@"35.PopView",@"TestViewController"],
                        @[@"36.SinaPopView"],
                        @[@"37.ImageWaterViewController---水印",@"ImageWaterViewController"],
                        @[@"38.ChangeTextColorViewController",@"ChangeTextColorViewController"],
                        @[@"39.NavigationBarViewController",@"NavigationBarViewController"],
                        @[@"40.ImgaePickerViewController",@"ImgaePickerViewController"],
                        @[@"41.ActionSheet",@"ActionSheet"]];
}

#pragma mark - UITableView Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _demoTitleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"HomeTableViewCell";
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell == nil) {
        cell = [[HomeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.titleLabel.text = _demoTitleArray[indexPath.row][0];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 1:
            [self getAddressBook];
            break;
        case 7:
            [self showCalender];
            break;
        case 18:
        {
            RxWebViewController* webViewController = [[RxWebViewController alloc] initWithUrl:[NSURL URLWithString:@"http://www.qq.com/"]];
            [self.navigationController pushViewController:webViewController animated:YES];
            break;
        }
        case 19:
        {
            LxDBAnyVar(self.view);
            break;
        }
        case 27:
        {
            [self showColumnView];
            break;
        }
        case 34:
        {
            [self showSinaPopView];
            break;
        }
        case 32:
        {
            [PellTableViewSelect addPellTableViewSelectWithWindowFrame:CGRectMake(self.view.bounds.size.width-100, 64, 150, 200)
                                                            selectData:@[@"扫一扫",@"加好友",@"创建讨论组",@"发送到电脑",@"面对面快传",@"收钱"] images:@[@"saoyisao.png",@"jiahaoyou.png",@"taolun.png",@"diannao.png",@"diannao.png",@"shouqian.png"] action:^(NSInteger index) {
                                                                NSLog(@"选择%ld",index);
                                                            } animated:YES];
        }
            break;
        case 39:
        {
            AS_Sheet *a = [[AS_Sheet alloc] initWithFrame:self.view.bounds titleArr:@[@"从手机相册选择", @"拍照", @"小视频"]];
            __weak typeof(a) weakA = a;
            a.Click = ^(NSInteger clickIndex) {
                switch (clickIndex) {
                    case 0:
                        NSLog(@"相册选择");
                        break;
                    case 1:
                        NSLog(@"拍照");
                        break;
                    case 2:
                        NSLog(@"小视频");
                        break;
                    default:
                        break;
                }
                [weakA hiddenSheet];
            };
            [self.navigationController.view addSubview:a];
        }
            break;
        default:
        {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            NSString *identifier = _demoTitleArray[indexPath.row][1];
            UIViewController *viewController = [[UIStoryboard storyboardWithName:identifier bundle:nil] instantiateViewControllerWithIdentifier:identifier];
            [self.navigationController pushViewController:viewController animated:YES];
        }
            break;
    }
}

// 2
- (void)getAddressBook {
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    NSArray *displayedItems = [NSArray arrayWithObjects:[NSNumber numberWithInt:kABPersonPhoneProperty],
                               [NSNumber numberWithInt:kABPersonEmailProperty],
                               [NSNumber numberWithInt:kABPersonBirthdayProperty], nil];
    
    
    picker.displayedProperties = displayedItems;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

// 8
- (void)showCalender {
    if (!_calendarView) {
        _calendarView = [[LDCalendarView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT)];
        [self.view addSubview:_calendarView];
        _calendarView.complete = ^(NSArray *result) {
            if (result) {
                
            }
        };
    }
    [self.calendarView show];
//    self.calendarView.defaultDates = _seletedDays;
}

// 网易下拉刷新事件
- (void)dropViewDidBeginRefreshing:(CCEaseRefresh *)refreshControl {
    double delayInSeconds = 3.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [refreshControl endRefreshing];
    });
}

// 27.CustomMenu
- (void)showSchoolList:(UIBarButtonItem *)barButtonItem {
    __weak __typeof(self) weakSelf = self;
    if (!self.menu) {
        self.menu = [[JHCustomMenu alloc] initWithDataArr:@[@"附近学校", @"联赛流程", @"其他联赛", @"校内群聊", @"邀请好友"] origin:CGPointMake(0, 0) width:125 rowHeight:44];
        _menu.delegate = self;
        _menu.dismiss = ^() {
            weakSelf.menu = nil;
        };
        _menu.arrImgName = @[@"item_school.png", @"item_battle.png", @"item_list.png", @"item_chat.png", @"item_share.png"];
        [self.view addSubview:_menu];
    } else {
        [_menu dismissWithCompletion:^(JHCustomMenu *object) {
            weakSelf.menu = nil;
        }];
    }
}

// 29.columnView
- (void)showColumnView {
    NSArray *selectedArray = @[@"头条",@"热点",@"体育",@"本地",@"财经",@"科技",@"图片",@"跟帖",@"直播",@"时尚",@"汽车",@"轻松一刻",@"汽车",@"端子",@"军事",@"房产",@"历史",@"家居",@"原创",@"游戏"];
    NSArray *optionalArray = @[@"NBA",@"画报",@"跑步",@"值得买",@"酒香",@"LOL",@"社会",@"暴雪游戏帖",@"云课堂",@"旅游",@"读书",@"葡萄酒",@"你照吗",@"移动互联",@"情感",@"博客",@"论坛",@"数码",@"国际足球",@"彩票",@"股票",@"哒哒",@"漫画"];
    
    ColumnViewController *vc = [[ColumnViewController alloc] init];
    vc.title = self.title;
    vc.view.frame = self.view.bounds;
    [vc.selectedArray addObjectsFromArray:selectedArray];
    [vc.optionalArray addObjectsFromArray:optionalArray];
//    [self.lcNavigationController pushViewController:vc];
    [self.navigationController pushViewController:vc animated:YES];
}

// 36.SinaPopView
- (void)showSinaPopView {
    BHBItem * item0 = [[BHBItem alloc]initWithTitle:@"Text" Icon:@"images.bundle/tabbar_compose_idea"];
    BHBItem * item1 = [[BHBItem alloc]initWithTitle:@"Albums" Icon:@"images.bundle/tabbar_compose_photo"];
    BHBItem * item2 = [[BHBItem alloc]initWithTitle:@"Camera" Icon:@"images.bundle/tabbar_compose_camera"];
    BHBItem * item3 = [[BHBItem alloc]initWithTitle:@"Check in" Icon:@"images.bundle/tabbar_compose_lbs"];
    BHBItem * item4 = [[BHBItem alloc]initWithTitle:@"Review" Icon:@"images.bundle/tabbar_compose_review"];
    BHBItem * item5 = [[BHBItem alloc]initWithTitle:@"More" Icon:@"images.bundle/tabbar_compose_more"];
    //第六个按钮是more按钮
    item5.isMore = YES;
    BHBItem * item6 = [[BHBItem alloc]initWithTitle:@"Friend Circle" Icon:@"images.bundle/tabbar_compose_friend"];
    BHBItem * item7 = [[BHBItem alloc]initWithTitle:@"Weibo Camera" Icon:@"images.bundle/tabbar_compose_wbcamera"];
    BHBItem * item8 = [[BHBItem alloc]initWithTitle:@"Music" Icon:@"images.bundle/tabbar_compose_music"];
    BHBItem * item9 = [[BHBItem alloc]initWithTitle:@"Blog" Icon:@"images.bundle/tabbar_compose_weibo"];
    BHBItem * item10 = [[BHBItem alloc]initWithTitle:@"Collection" Icon:@"images.bundle/tabbar_compose_transfer"];
    BHBItem * item11 = [[BHBItem alloc]initWithTitle:@"Voice" Icon:@"images.bundle/tabbar_compose_voice"];
    
    [BHBPopView showToView:self.view withItems:@[item0,item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11]andSelectBlock:^(BHBItem *item, NSInteger index) {
        NSLog(@"%ld,选中%@",index,item.title);
    }];
}

- (void)jhCustomMenu:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"select: %ld", indexPath.row);
}

- (void)setDisViewButtonsNum:(int)num{
    [_disView recoverBotton];
    for (UIView *btn in _disView.btns) {
        [btn removeFromSuperview];
    }
    NSMutableArray *marr = [NSMutableArray array];
    for (int i = 0; i< num; i++) {
        UIButton *btn = [UIButton new];
        NSString *name = [NSString stringWithFormat:@"SC%d",i];
        [btn setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
        [marr addObject:btn];
        btn.tag = i;
        [btn addTarget:self action:@selector(buttonTagget:) forControlEvents:UIControlEventTouchUpInside];
    }
    _disView.btns = [marr copy];
}

-(void)buttonTagget:(UIButton *)sender{
    
}

-(void)dd{
    double delayInSeconds = 3;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self.refresh endRefreshing];
    });
}

- (void)addGuideView {
    markView = [[GuideView alloc]initWithFrame:self.view.bounds];
    markView.fullShow = YES;
    markView.model = GuideViewCleanModeRoundRect;
    markView.showRect = CGRectMake(0, 0, 120, 80);
    [self.view addSubview:markView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.titleTextAttributes = @{
                                                                    NSForegroundColorAttributeName : [UIColor whiteColor]
                                                                    };
    [self.pickerView addGestureRecognizersToNavigationBar:self.navigationController.navigationBar];
}

// AYSlidingPickerView
- (void)setUpPickerView {
    NSDictionary *colors = @{
                             @"Red" : [UIColor colorWithRed:0.91f green:0.3f blue:0.24f alpha:1],
                             @"Green" : [UIColor colorWithRed:0.18f green:0.8f blue:0.44f alpha:1],
                             @"Blue" : [UIColor colorWithRed:0.2f green:0.6f blue:0.86f alpha:1],
                             @"Magenta" : [UIColor colorWithRed:0.61f green:0.35f blue:0.71f alpha:1],
                             @"Yellow" : [UIColor colorWithRed:1 green:0.8f blue:0 alpha:1]
                             };
    
    NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:colors.count];
    for (NSString *color in colors) {
        AYSlidingPickerViewItem *item = [[AYSlidingPickerViewItem alloc] initWithTitle:color handler:^(BOOL completed) {
            self.view.backgroundColor = colors[color];
            self.navigationController.navigationBar.barTintColor = [self darkerColorForColor:self.view.backgroundColor];
        }];
        [items addObject:item];
    }
    
    self.pickerView = [AYSlidingPickerView sharedInstance];
    self.pickerView.mainView = self.view;
    self.pickerView.items = items;
    self.pickerView.selectedIndex = 1;
    self.pickerView.closeOnSelection = YES;
    
    self.view.backgroundColor = colors[[colors allKeys][self.pickerView.selectedIndex]];
    self.navigationController.navigationBar.barTintColor = [self darkerColorForColor:self.view.backgroundColor];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self.pickerView action:@selector(show)];
}

#pragma mark Helpers

- (UIColor *)darkerColorForColor:(UIColor *)color {
    CGFloat r, g, b, a;
    if ([color getRed:&r green:&g blue:&b alpha:&a]) {
        return [UIColor colorWithRed:MAX(r - 0.2f, 0) green:MAX(g - 0.2f, 0) blue:MAX(b - 0.2f, 0) alpha:a];
    }
    return nil;
}

@end
